<template>
  <div>
    <h1>损耗监控看板</h1>
    <!-- 查询表单和按钮 -->
    <div class="search-form">
      <div class="search-form-put">
        <div class="form-row">
            <label>坯布类型:</label>
            <vxe-select v-model="peiType" placeholder="请选择坯布类型">
              <vxe-option
                  v-for="type in peiTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value">
              </vxe-option>
            </vxe-select>
            <label>客户:</label>
            <vxe-input type="text" v-model="clothLineName" >客户名称</vxe-input>
            <label>布行面料编码:</label>
            <vxe-input type="text" v-model="productCode" >布行面料名称</vxe-input>
            <label>布行面料名称:</label>
            <vxe-input type="text" v-model="productName" >布行面料名称</vxe-input>
        </div>

        <div class="form-row">
            <label>开始时间:</label>
            <calendar v-model="startDate" show-date-only :disabled-days-of-week="disabled" :format="format"
                      :clear-button="clear" :lang="lang" :position="position"
                      :pane="1" :range-bus="getBus" :range-status="1"></calendar>
            <label>至:</label>
            <calendar v-model="endDate" show-date-only :disabled-days-of-week="disabled" :format="format"
                      :clear-button="clear" :lang="lang" :position="position"
                      :pane="1" :range-bus="getBus" :range-status="2"></calendar>
            <label>损耗率标准:</label>
            <vxe-input type="text" v-model="outlossrate" >损耗率标准:</vxe-input>
        </div>
      </div>
      <div class="search-form-button">
        <vxe-button type="submit" @click="handleSearch">查询</vxe-button>
        <vxe-button @click="$refs.xTable.setAllRowExpand(true)" >展开所有行</vxe-button>
        <vxe-button @click="$refs.xTable.clearRowExpand()">折叠所有行</vxe-button>
        <vxe-button @click="exportData">导出</vxe-button>
      </div>
    </div>
    <vxe-table
        resizable
        border
        ref="xTable"
        class="mytable-scrollbar"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        v-loading="loading"
        :height="tableHeight"
        :expand-config="{iconOpen: 'vxe-icon-square-minus'}"
        :data="tableData">
      <vxe-column type="expand" width="80" align="center">
        <template #content="{ row }">
          <div class="expand-wrapper">
            <vxe-table
                resizable
                border
                :height="getInnerTableHeight(row)"
                :data="rowData2Map[`${row.cloth_line_name}#${row.product_code}#${row.degree_of_staining_code}`]">
              <vxe-column type="seq" width="60" title="明细序号" show-header-overflow="title" ></vxe-column>
              <vxe-column field="dyelot_code" title="缸号" sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="cloth_line_name" title="客户" sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="product_code" title="布行面料编号" sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="product_name" title="布行面料名称" sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="degree_of_staining_code" title="染色程度编号" :visible="false"></vxe-column>
              <vxe-column field="degree_of_staining_name" title="染色程度名称" sortable show-header-overflow="title" ></vxe-column>

              <vxe-column field="label_print_gsm" title="克重要求" show-header-overflow="title" sortable/>
              <vxe-column field="ingredients_type" title="成份分类" show-header-overflow="title" sortable/>
              <vxe-column field="reset_source" title="回修类型" show-header-overflow="title" sortable/>

              <vxe-column field="in_date" title="日期" sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="label_color_name" title="码卡颜色" sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="workmanshipPayProjects" title="加工项目" align="left"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="fabric_sum" title="成品数量" align="right"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="fabric_label_weight_sum" title="成品重量" align="right"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="pi_sum" title="配坯数量" align="right"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="xima_sum" title="配坯重量" align="right"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="kongcha" title="空差" align="right"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="tube_weight" title="纸管" align="right"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="loss_rate" title="损耗率" align="right"  sortable show-header-overflow="title" ></vxe-column>
              <vxe-column field="remarks" title="备注" show-header-overflow="title" ></vxe-column>
            </vxe-table>
          </div>
        </template>
      </vxe-column>
      <vxe-column type="seq" title="序号"  show-header-overflow="title"  ></vxe-column>
      <vxe-column field="cloth_line_name" title="客户" show-header-overflow="title" align="left" sortable/>
      <vxe-column field="pei_type" title="坯布类型" sortable show-header-overflow="title" ></vxe-column>
      <vxe-column field="product_code" title="布行面料编号" show-header-overflow="title" align="left" sortable/>
      <vxe-column field="product_name" title="布行面料名称" show-header-overflow="title" align="left" sortable/>
      <vxe-column field="degree_of_staining_code" title="染色程度编号" show-header-overflow="title" :visible="false" sortable/>
      <vxe-column field="degree_of_staining_name" title="染色程度名称" show-header-overflow="title" sortable/>

      <vxe-column field="label_print_gsm" title="克重要求" show-header-overflow="title" sortable/>
      <vxe-column field="workmanship_pay_project_name" title="收费项目" show-header-overflow="title" sortable/>
      <vxe-column field="ingredients_type" title="成份分类" show-header-overflow="title" sortable/>
      <vxe-column field="reset_source" title="回修类型" show-header-overflow="title" sortable/>
      <vxe-column field="remarks" title="备注" show-header-overflow="title" sortable/>
      <vxe-column field="fabric_sum" title="成品数量" show-header-overflow="title" sortable/>

      <vxe-column field="detail_count" title="明细数"  align="right"  show-header-overflow="title" sortable/>
      <vxe-column field="avg_loss_rate" title="平均损耗率" align="right"  show-header-overflow="title" sortable/>
      <vxe-column field="out_loss_rate" title="异常损耗率明细条数" align="left"  show-header-overflow="title" sortable/>
    </vxe-table>
  </div>
</template>
<script>
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver';
import Vue, {ref} from "vue"; // 假设这是你的 API 服务
import Calendar from 'vue2-slot-calendar';
import {expandRowsH, expandRowsD, expandRowsExportD} from "@/services/DataService";


export default {
  name: "ExpandRows",
  components: {
    calendar: Calendar
  },
  watch:{
    peiType(peiType){
      this.peiType = peiType.trim();
    },
    clothLineName(clothLineName){
      this.clothLineName = clothLineName.trim();
    },
    productCode(productCode){
      this.productCode = productCode.trim();
    },
    productName(productName){
      this.productName = productName.trim();
    }
  },
  data () {
    return {
      loading: true,
      tableHeight: 0, // 响应式属性，用于存储表格高度
      tableDHeight: 0,
      tableData: [], // 初始化为空数组
      rowData2Map: {}, // 用于存储每行name对应的tableData2
      productName: "",
      outlossrate: "100",
      productCode: "",
      clothLineName: "",
      peiType: "",
      peiTypes: [
        { value: '', label: '' },
        { value: '坯布', label: '坯布' },
        { value: '色布', label: '色布' },
      ],
      disabled: [],
      startDate: ref(new Date()),
      endDate: ref(new Date()),
      format: "yyyy-MM-dd",
      clear: false,
      placeholder: "Start Date",
      position: "left",
      lang: "",
      bus: new Vue(),

    }
  },
  async created() {
    try {
      const currentDate = new Date().toISOString().split('T')[0];
      this.startDate = currentDate;
      this.endDate = currentDate;
      this.expandRows(this.peiType,this.clothLineName,this.productCode,this.productName,this.startDate,this.endDate);
      this.loading = false;
    } catch (error) {
      this.loading = false;
      console.error('获取tableData失败:', error);
    }
  },
  async mounted () {
    document.title = '损耗监控看板';
    this.setWindowHeight(); // 设置初始高度
    window.addEventListener('resize', this.setWindowHeight); // 监听窗口大小变化
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setWindowHeight); // 组件销毁前移除监听器
  },
  methods:{
    // 根据外部表格的行数据返回内部表格的高度
    getInnerTableHeight(row) {
      // 例如，假设我们有一个字段叫做'innerHeight'在row中定义了内部表格的高度
      const key = `${row.cloth_line_name}#${row.product_code}#${row.degree_of_staining_code}`;
      // console.log(key)
      const key_length = this.rowData2Map[key].length;
      let innerHeight = 150;
      if (key_length==1){
        innerHeight = 150;
      }else if (key_length>=2&&key_length<=9){
        innerHeight = 150+(key_length-1)*45;
      }else{
        innerHeight = 500;
      }
      return innerHeight + 'px'; // 返回字符串，因为CSS需要像素值作为字符串
    },
    getBus() {
      return this.bus;
    },
    async handleSearch() {
      this.loading = true; // 开始加载前设置loading为true
      try {
        await this.expandRows(this.peiType,this.clothLineName,this.productCode,this.productName,this.startDate, this.endDate); // 等待expandRows完成
      } catch (error) {
        console.error('获取tableData失败:', error);
      } finally {
        this.loading = false; // 无论expandRows是否成功，都设置loading为false
      }
    },
    async expandRows(peiType,clothLineName,productCode,productName,startDate,endDate) {
      // 获取接口数据
      const res = await expandRowsH(peiType,clothLineName,productCode,productName,startDate,endDate,this.outlossrate);
      if (res!=undefined){

        // 假设res是一个包含多个条目的数组
        const promises = res.map(item => {
          // 这里我们假设loadTableData2返回一个Promise
          return this.loadTableData2(item.reset_source,item.pei_type,item.cloth_line_name,item.product_code,item.degree_of_staining_code,startDate,endDate);
        });

        // 等待所有tableData2加载完成
        await Promise.all(promises);

        // 所有数据加载完成后，更新tableData
        this.tableData = res.map(item => ({
              cloth_line_name: item.cloth_line_name,
              pei_type: item.pei_type,
              product_code: item.product_code,
              product_name: item.product_name,
              degree_of_staining_code: item.degree_of_staining_code,
              degree_of_staining_name: item.degree_of_staining_name,
              detail_count: item.detail_count,
              avg_loss_rate: item.avg_loss_rate,
              out_loss_rate: item.out_loss_rate,

              label_print_gsm: item.label_print_gsm,
              workmanship_pay_project_name: item.workmanship_pay_project_name,
              ingredients_type: item.ingredients_type,
              reset_source: item.reset_source,
              remarks: item.remarks,
              fabric_sum: item.fabric_sum,
        }));

      }

    },
    async loadTableData2(reset_source,pei_type,cloth_line_name,product_code,degree_of_staining_code,startDate,endDate) {
      // 假设获取tableData2的接口地址是'api/tableData2/:id'
      try {

        const res2 = await expandRowsD(reset_source,pei_type,cloth_line_name,product_code,degree_of_staining_code,startDate,endDate);

        const key = `${cloth_line_name}#${product_code}#${degree_of_staining_code}`;

        // 检查 key 是否已经在 rowData2Map 中，如果没有则初始化为空数组
        this.rowData2Map[key] = [];

        const size = res2.length;
        for (let index = 0; index < size; index++) {
          this.rowData2Map[key].push({
            dyelot_code: res2[index].dyelot_code,
            cloth_line_name: res2[index].cloth_line_name,
            product_code: res2[index].product_code,
            product_name: res2[index].product_name,
            degree_of_staining_code: res2[index].degree_of_staining_code,
            degree_of_staining_name: res2[index].degree_of_staining_name,
            label_color_name: res2[index].label_color_name,
            fabric_sum: res2[index].fabric_sum,
            fabric_label_weight_sum: res2[index].fabric_label_weight_sum,
            pi_sum: res2[index].pi_sum,
            xima_sum: res2[index].xima_sum,
            kongcha: res2[index].kongcha,
            tube_weight: res2[index].tube_weight,
            loss_rate: res2[index].loss_rate,
            remarks: res2[index].remarks=="None"?"":res2[index].remarks,
            in_date: res2[index].in_date,
            workmanshipPayProjects: res2[index].workmanshipPayProjects,

            label_print_gsm: res2[index].label_print_gsm,
            ingredients_type: res2[index].ingredients_type,
            reset_source: res2[index].reset_source,
          });
        }
      } catch (error) {
            console.error(`获取cloth_line_name、product_code和degree_of_staining_code为${cloth_line_name}#${product_code}#${degree_of_staining_code}的tableData2失败:`, error);
      }
    },
    setWindowHeight() {
      // 计算可用高度，这里只是一个示例，你可能需要根据你的布局进行调整
      const windowHeight = window.innerHeight;
      // 假设你要留给表格之外的内容（如页眉、页脚等）100px的高度
      this.tableHeight = windowHeight - 230;
    },
    formatDate(dateString) {
      // 解析ISO格式的日期字符串
      const date = new Date(dateString);
      // 格式化日期为YYYY-MM-DD格式
      return `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`;
    },
    getColumnNumber(colLetter) {
      // 将列字母转换为从 1 开始的列索引
      let columnNumber = 0;
      for (let i = 0; i < colLetter.length; i++) {
        columnNumber = (columnNumber * 26) + (colLetter.charCodeAt(i) - 'A'.charCodeAt(0) + 1);
      }
      return columnNumber;
    },
    async exportData() {
      try {
        this.loading = true;
        // 发送请求并获取数据
        const dataH = await expandRowsH(this.peiType,this.clothLineName,this.productCode,this.productName,this.startDate,this.endDate,this.outlossrate);
        const dataD = await expandRowsExportD(this.peiType,this.clothLineName,this.productCode,this.productName,this.startDate,this.endDate);

        // 排序
        dataH.sort((a, b) => {
          if (a.product_code === b.product_code) {
            // 如果 product_code 相同，则按 degree_of_staining_code 排序
            return a.degree_of_staining_code.localeCompare(b.degree_of_staining_code);
          }
          // 否则按 product_code 排序
          return a.product_code.localeCompare(b.product_code);
        });
        dataD.sort((a, b) => {
          if (a.product_code === b.product_code) {
            // 如果 product_code 相同，则按 degree_of_staining_code 排序
            return a.degree_of_staining_code.localeCompare(b.degree_of_staining_code);
          }
          // 否则按 product_code 排序
          return a.product_code.localeCompare(b.product_code);
        });

        // 转换你的数据以匹配标题
        const dataSheet1 = dataH.map((item, index) => ({
          序号: index+1,
          客户: item.cloth_line_name,
          坯布类型: item.pei_type,
          布行面料编号: item.product_code,
          布行面料名称: item.product_name,
          染色程度名称: item.degree_of_staining_name,

          克重要求: item.label_print_gsm,
          加工项目: item.workmanship_pay_project_name,
          成份分类: item.ingredients_type,
          回修类型: item.reset_source,
          成品数量: item.fabric_sum,

          平均损耗率: item.avg_loss_rate,
          异常损耗率明细条数: item.out_loss_rate
        }));
        const dataSheet2 = dataD.map((item, index) => ({
          序号: index+1,
          缸号: item.dyelot_code,
          客户: item.cloth_line_name,
          布行面料编号: item.product_code,
          布行面料名称: item.product_name,
          染色程度名称: item.degree_of_staining_name,
          日期:  this.formatDate(item.in_date),
          码卡颜色: item.label_color_name,
          收费项目: item.workmanshipPayProjects,
          克重要求: item.label_print_gsm=="None"?"":item.label_print_gsm,
          成份分类: item.ingredients_type=="None"?"":item.ingredients_type,
          回修类型: item.reset_source=="None"?"":item.reset_source,
          成品数量: item.fabric_sum,
          成品重量: item.fabric_label_weight_sum,
          配坯数量: item.pi_sum,
          配坯重量: item.xima_sum,
          空差: item.kongcha,
          纸管: item.tube_weight,
          损耗率: item.loss_rate,
          备注: item.remarks=="None"?"":item.remarks
        }));

        const workbook = XLSX.utils.book_new();
        const worksheet1 = XLSX.utils.json_to_sheet(dataSheet1);
        const worksheet2 = XLSX.utils.json_to_sheet(dataSheet2);

        const columnWidthsH = [5, 15, 30, 15,10];
        const columnWidthsD = [5, 15,15, 15, 30, 15, 20, 10, 15, 10, 15, 10, 10, 15, 5];

        worksheet1['!cols'] = columnWidthsH.map(width => ({ wch: width }));
        worksheet2['!cols'] = columnWidthsD.map(width => ({ wch: width }));

        //添加样式

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet1, '汇总');
        XLSX.utils.book_append_sheet(workbook, worksheet2, '明细');


        // 生成 Excel 文件的 Blob 对象
        const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

        //触发下载
        const blob = new Blob([wbout], { type: 'application/octet-stream' });
        saveAs(blob, '损耗监控看板_'+Date.now()+'.xlsx');
        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('Error exporting data:', error);
      }
    },
  },
}
</script>
<style scoped>
.expand-wrapper {
  padding: 20px;
}
.search-form {
  margin-bottom: 10px;
}
.search-form-put{
  padding: 5px;
}
.search-form-button{
  padding: 5px;
}
.form-row{
  padding: 5px;
}
/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
  background-color: #FFFFFF;
}
/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
  background-color: #bfbfbf;
  border-radius: 5px;
  border: 1px solid #F1F1F1;
  box-shadow: inset 0 0 6px rgba(0,0,0,.3);
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
  background-color: #A8A8A8;
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
  background-color: #787878;
}
/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
  background-color: #FFFFFF;
}
</style>
